<template>
    <TopNav />

    <div class="main_wrap" style="background-color: #f5f5f5;">

        <div class="top">
            <div class="row">

                <div class="form_item">
                    <span class="label">会&ensp;&ensp;员：</span>
                    <el-input v-model="memberPhoneNumber" @click="openPhoneNumber" size="large" style="width: 200px;"
                        placeholder="请输入手机号" />
                </div>

            </div>
            <div class="row" style="padding-bottom: 10px;">
                <div class="form_item">
                    <span class="label">支付时间：</span>
                    <el-date-picker v-model="strTime" ref="startTimeRef" format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" :clearable="false" type="datetime" placeholder="请选择日期"
                        size="large" style="width: 200px;" />
                </div>
                <div style="margin-right:10px;">至</div>
                <div class="form_item">

                    <el-date-picker v-model="endTime" ref="endTimeRef" format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" :clearable="false" type="datetime" placeholder="请选择日期"
                        size="large" style="width: 200px;" />
                </div>

                <el-radio-group v-model="dayType" size="large" @change="changeDateTypes">
                    <el-radio-button label="今天" value="0" />
                    <el-radio-button label="昨天" value="1" />
                    <el-radio-button label="近7天" value="2" />
                </el-radio-group>

                <el-button size="large" type="primary" :icon="Search" @click="search"
                    style="margin-left:10px">查询</el-button>

            </div>
        </div>
        <div class="main">

            <div class="my_table" ref="myTableRef">
                <el-table @current-change="handleCurrentChange" ref="singleTableRef" highlight-current-row
                    :header-cell-style="{ backgroundColor: '#f5f7fa', }" stripe :data="currentPageTableData">
                    <el-table-column type="index" :index="indexMethod" width="50" />
                    <el-table-column prop="stateText" label="状态" min-width="70" />
                    <el-table-column prop="orderTime" label="下单时间" min-width="118" />
                    <el-table-column prop="number" label="订单号" min-width="118" />
                    <el-table-column prop="memberPhoneNumber" label="会员" />
                    <el-table-column prop="receivableAmount" label="应收金额" />
                    <el-table-column prop="capital" label="本金" width="90" />
                    <el-table-column prop="giveCash" label="赠金" width="90" />


                    <el-table-column label="操作" width="88" style="padding: 0;">
                        <template #default="scope">
                            <el-button type="primary" @click="openDesc(scope.row)">
                                详情
                            </el-button>

                        </template>
                    </el-table-column>


                </el-table>
            </div>
            <div class="bottom">

                <div class="btns">
                    <el-button size="large" type="primary" @click="prev" :disabled="currentPage <= 1">上一页</el-button>
                    <el-button size="large" type="primary" @click="next"
                        :disabled="currentPage >= Math.ceil(pageTableData.flat().length / pageSize)">下一页</el-button>
                    <el-button size="large" type="success" :disabled="!currentRow" @click="printTicket">打印小票</el-button>
                </div>
            </div>
        </div>
        <!--打印wrap-->
        <div ref="domDiv" class="print_wrap" :class="(currentScaleType=='2'||currentScaleType=='3')?'tuoliduo':''" v-if="currentRow && orderDesc" style="padding-left:10px"
            :style="{ paddingLeft: paperLeft, paddingRight: paperRight }">
            <div class="title">欢迎光临[一手店]</div>
            <div>重打小票</div>
            <div>单号：{{ currentRow.number }}</div>
            <div>店铺：{{ currentRow.shopName }}</div>
            <div>电话：{{ userInfo.user_account }}</div>
            <div>收银：{{ userInfo.user_name }}</div>
            <div>时间：{{ currentRow.orderTime }}</div>
            <div class="line"></div>


            <div class="flex">
                <div>会员充值</div>
                <div>&yen;{{ }}</div>
            </div>
            <div class="item" v-for="item in orderDesc.orderDetailVos" :key="item.goodsID">
                <div>{{ item.goodsName }}</div>
                <div class="flex">
                    <div>{{ item.retailPrice }} x{{ item.quantity }}</div>
                    <div>¥{{ item.payAmount }}</div>
                </div>
                <div class="discount" v-if="NP.minus(item.totalPrice, item.payAmount) != 0">(原金额{{ item.totalPrice }}
                    已优惠{{
                        NP.minus(item.totalPrice, item.payAmount) }})</div>
            </div>
            <div class="line"></div>

            <div class="flex">
                <div>订单金额</div>
                <div>¥合计金额？</div>
            </div>
            <div class="flex">
                <div>应收金额</div>
                <div>¥合计金额？</div>
            </div>
            <div class="line"></div>
            <div class="flex" v-for="item in orderDesc.orderPayInfoVos" :key="item.payType">
                <div>{{ item.payTypeText }}</div>
                <div>¥{{ item.payAmount }}</div>
            </div>
            <div class="line"></div>
            <div>多谢惠顾，欢迎下次光临</div>
            <div>客服电话：4006365999</div>
            <div class="margin_bottom_placeholder"></div>
        </div>

    </div>

    <!--搜索键盘-->
    <SearchKeyboard keyboardContainerClass="rechargequery_ordernumber_id" v-model="isShowSearchKeyboard" title="请输入订单编号"
        @onChange="onSearchKeyboardChange" class="custom_search_class">

    </SearchKeyboard>
    <!--会员手机号键盘-->
    <PhoneKeyboard keyboardContainerClass="rechargequery_phonenumber_id" ref="phoneKeyboardRef"
        v-model="isShowPhoneKeyboard" title="请输入手机号" :inputVal="memberPhoneNumber" @onConfirmPhone="confirmPhone"
        @onChange="onPhoneKeyboardChange" class="custom_phone_class" />


    <!--充值详情-->
    <el-dialog v-model="orderDescDialogVisible" class="order_desc_dialog" title="充值详情" width="800">
        <el-descriptions size="large" title="">
            <el-descriptions-item label="订单号">{{ currentRow?.number }}</el-descriptions-item>
            <el-descriptions-item label="支付方式"
                v-if="orderDesc && orderDesc.orderPayInfoVos && orderDesc.orderPayInfoVos[0]">{{
                        orderDesc.orderPayInfoVos[0].payTypeText || '' }}</el-descriptions-item>
            <el-descriptions-item label="会员">{{ currentRow?.memberPhoneNumber }}</el-descriptions-item>
            <el-descriptions-item label="本金">{{ currentRow?.capital }}</el-descriptions-item>
            <el-descriptions-item label="赠金">{{ currentRow?.giveCash }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ currentRow?.orderTime }}</el-descriptions-item>
            <el-descriptions-item label="应收金额">{{ currentRow?.receivableAmount }}</el-descriptions-item>
        </el-descriptions>

        <el-divider style="margin:0" />
        <div class="title">赠送优惠券</div>
        <el-table border :header-cell-style="{ backgroundColor: '#f5f7fa', }" stripe
            :data="orderDesc?.orderMemberCouponVos">
            <el-table-column type="index" label="序" width="50" />
            <el-table-column prop="couponName" label="优惠券名称" />
            <el-table-column prop="couponQuantity" label="数量" />

        </el-table>

        <template #footer>
            <div class="dialog-footer">
                <el-button size="large" v-if="currentRow?.state === '0'" type="success" @click="refreshOrder">
                    刷新
                </el-button>
                <el-button size="large" v-if="currentRow?.state === '1'" type="warning"
                    @click="toRefound">
                    退款
                </el-button>
                <el-button size="large" type="primary" @click="orderDescDialogVisible = false">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!--确认退款提示弹窗-->
    <el-dialog v-model="refoundDialogVisible" class="order_desc_dialog" title="确认退款?" width="800">
        <template #footer>
            <div class="dialog-footer">
                <el-button size="large" @click="refoundDialogVisible = false">
                    取消
                </el-button>
                <el-button size="large" type="primary" @click="confirmRefound">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>


<script setup lang='ts'>
// @ts-nocheck
import domtoimage from 'dom-to-image'; //dom转图片
import { getRecharge, getRechargeDesc, refound } from '@renderer/api/rechargequery'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { onMounted, ref, watch, watchEffect, computed, nextTick } from 'vue'
import { getDateTimeString } from '@renderer/utils'
import SearchKeyboard from '@renderer/components/SearchKeyboard.vue'
import PhoneKeyboard from '@renderer/components/PhoneKeyboard.vue'
import { useUserStore } from '@renderer/store/user'
import { storeToRefs } from 'pinia'
import { useRoute } from 'vue-router'
import NP from "number-precision";
import { rechargeRefresh } from '@renderer/api/rechargequery';
const number = ref('')
const memberPhoneNumber = ref('')
const tableData = ref([])
const phoneKeyboardRef = ref()
const pageSize = ref(0) //每页条数
const currentPage = ref(1)
const currentRow = ref()
const userStore = useUserStore()
const { userInfo, shopInfo,paperLeft, paperRight,currentScaleType,currentTime } = storeToRefs(userStore)
const saleOrganizationID = userInfo.value.user_organizationId
const myTableRef = ref()
const singleTableRef = ref()
const orderDescDialogVisible = ref(false)
const orderDesc = ref()
let domDiv = ref(null)
const route = useRoute()
const refoundDialogVisible = ref(false) //退款提示弹窗
onMounted(() => {
    memberPhoneNumber.value = route.query.phone
    console.log(route)
    let tableHeight = myTableRef.value.offsetHeight
    let singleRowHeight = 49 //每行高度
    pageSize.value = Math.floor(tableHeight / singleRowHeight) - 1 //每页最多显示行数(-1 是减去header)
})

function toRefound() {
    // console.log(currentRow.value.payTime.split(' ')[0])
    // console.log(currentTime.value)
    // console.log(getDateTimeString(currentTime.value))
    if(currentRow.value.payTime.split(' ')[0]!=getDateTimeString(currentTime.value)){
           ElMessage({
            message: '充值退款不能超过1天',
            type: 'warning',
        })
        return false
    }
   

    refoundDialogVisible.value = true
}

//确认退款
async function confirmRefound() {
    try {
        const { data, msg } = await refound(currentRow.value.id)
        ElMessage({
            message: msg,
            type: 'success',
        })

        //修改当前行状态 为退款
        const foundIndex = tableData.value.findIndex(item => item.id === currentRow.value.id)
        if (foundIndex) {
            tableData.value[foundIndex] = { ...tableData.value[foundIndex], state: "9", stateText: "退款" }
        }
        orderDescDialogVisible.value = false

    } catch (error) {
        console.log(error)
    } finally {
        refoundDialogVisible.value = false
    }

}

//刷新订单
async function refreshOrder() {
    try {
        const refreshMemberRechargeCouponAdds = orderDesc.value.orderMemberCouponVos.map(item => ({ couponID: item.couponID, couponQuantity: item.couponQuantity }))
        const { memberID,capital, giveCash, memberPhoneNumber, shopID, saleOrganizationName, shopName,id:orderID,number   } = currentRow.value
        const organizationID = currentRow.value.saleOrganizationID
        const reqData = {
            memberID,
            orderID,
            saleOrganizationID: organizationID,
            shopID,
            number,
            capital,
            giveCash,
            memberPhoneNumber,
            occurrencePoint: 'POS',
            saleOrganizationName,
            shopName,
            refreshMemberRechargeCouponAdds
        }
        try {
            const { msg } = await rechargeRefresh(reqData)
            ElMessage({
                message: msg,
                type: 'success',
            })
            orderDescDialogVisible.value = false
            search()
        } catch (error) {

        }
    } catch (error) {

    }
}


//分页
function paginateData(data, pageSize) {
    const pages = [];
    for (let i = 0; i < data.length; i += pageSize) {
        pages.push(data.slice(i, i + pageSize));
    }
    return pages;
}

function openPhoneNumber() {
    isShowPhoneKeyboard.value = true

    nextTick(() => {
        phoneKeyboardRef.value && phoneKeyboardRef.value.setKeyboardInput(memberPhoneNumber.value)
    })

}

function onPhoneKeyboardChange(val) {
    //console.log(val)
}

function prev() {
    if (currentPage.value <= 1) return
    currentPage.value--
}
function next() {
    if (currentPage.value >= pageTableData.value.length) return
    currentPage.value++
}
//计算序号
function indexMethod(index) {
    return (currentPage.value - 1) * pageSize.value + index + 1
}

//切换选中行
const handleCurrentChange = (val) => {
    console.log(val)
    currentRow.value = val
}

//查询详情
async function getDesc(row) {

    const orderID = row.id
    try {
        const { data } = await getRechargeDesc(saleOrganizationID, orderID)
        orderDesc.value = data
    } catch (error) {
        console.log(error)
    }

}

//查看详情
async function openDesc(row) {
    await getDesc(row)
    orderDescDialogVisible.value = true
}

//dom-to-image
function getDomToImg(node,) {
    domtoimage.toPng(node,)
        .then(function (dataUrl) {
            console.log(dataUrl)
            const base64ImageData = dataUrl.replace(/^data:image\/png;base64,/, '');
            window.electron.ipcRenderer.send('base64ImageData', { data: base64ImageData })
        })
        .catch(function (error) {
            console.error('oops, something went wrong!', error);
        });
}



//打印小票
async function printTicket() {
    //console.log(currentRow.value)

    if (currentRow.value) {
        await getDesc(currentRow.value)

        getDomToImg(domDiv.value)
    } else {

        console.log('请选择订单')
    }
}



//当前页数据
const currentPageTableData = computed(() => {
    return pageTableData.value[currentPage.value - 1] || []
})

const dayType = ref('0')

//今天、昨天、近7天切换
function changeDateTypes(val) {
    if (val === '0') {
        setToday()
    } else if (val === '1') {
        setYesterday()
    } else if (val === '2') {
        setLastWeek()
    }
}

//根据日期设置按钮组选中状态
function setBtnsTypeByDate() {
    const todayStr = getDateTimeString(new Date().getTime())
    const yesterdayStr = getDateTimeString(new Date().getTime() - 3600 * 1000 * 24)
    const lastWeekDayStr = getDateTimeString(new Date().getTime() - 3600 * 1000 * 24 * 6)
    if (strTime.value === todayStr + ' 00:00:00' && endTime.value === todayStr + ' 23:59:59') {
        dayType.value = '0'
    } else if (strTime.value === yesterdayStr + ' 00:00:00' && endTime.value === yesterdayStr + ' 23:59:59') {
        dayType.value = '1'
    } else if (strTime.value === lastWeekDayStr + ' 00:00:00' && endTime.value === todayStr + ' 23:59:59') {
        dayType.value = '2'
    } else {
        dayType.value = ''
    }
}

const today = getDateTimeString(new Date().getTime())
const strTime = ref(today + ' 00:00:00')
const endTime = ref(today + ' 23:59:59')

//const endDefaultTime = ref('2024-09-08 23:59:59') //默认时间23:59:59 前面的日期没有用

const startTimeRef = ref()
const endTimeRef = ref()

const isShowSearchKeyboard = ref(false)
function onSearchKeyboardChange(val) {
    number.value = val
}

const isShowPhoneKeyboard = ref(false)
function confirmPhone(val) {
    memberPhoneNumber.value = val
    phoneKeyboardRef.value && phoneKeyboardRef.value.setKeyboardInput(memberPhoneNumber.value)
}

//日期改变后直接关闭弹窗
watch(strTime, () => {
    startTimeRef.value.handleClose()
    setBtnsTypeByDate()
})
watch(endTime, () => {
    endTimeRef.value.handleClose()
    setBtnsTypeByDate()
})
function search() {
    if (strTime.value && endTime.value && new Date(endTime.value).getTime() < new Date(strTime.value).getTime()) {

        endTime.value = ''
        ElMessage({
            message: '结束时间不能小于开始时间',
            type: 'warning',
        })
        return
    }
    currentPage.value = 1
    queryLog()
}
async function queryLog() {



    const reqData = {
        saleOrganizationID,
        phoneNumber: memberPhoneNumber.value,
        strTime: strTime.value,
        endTime: endTime.value,
        shopID:shopInfo.value.shopID
    }
    try {
        const { data } = await getRecharge(reqData)
        
        tableData.value = data
    } catch (error) {
        console.log(error)
    }


}
const pageTableData = computed(() => { //分页后的数据
    return paginateData(tableData.value, pageSize.value)
})
function setToday() { //将日期设为今天
    const dateString = getDateTimeString(new Date().getTime())
    strTime.value = dateString + ' 00:00:00'
    endTime.value = dateString + ' 23:59:59'

}

function setYesterday() { //将日期设为昨天昨天
    const dateString = getDateTimeString(new Date().getTime() - 3600 * 1000 * 24)
    strTime.value = dateString + ' 00:00:00'
    endTime.value = dateString + ' 23:59:59'

}
function setLastWeek() { //将日期设为近7天

    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
    const startDateString = getDateTimeString(new Date(start).getTime())
    strTime.value = startDateString + ' 00:00:00'
    endTime.value = getDateTimeString(new Date().getTime()) + ' 23:59:59'
}

</script>
<style lang='scss'>
.custom_search_class {
    left: 0 !important;
    top: 130px !important;
    bottom: unset;
}

//手机号键盘
.custom_phone_class {
    left: 430px !important;
}


.order_desc_dialog {
    .title {
        font-size: 16px;
        padding: 10px 0;
    }
}
</style>
<style scoped lang='scss'>
#app {
    overflow: hidden;
}

.main_wrap {
    padding: 0;
    overflow: hidden;
    position: relative;

    .top {
        padding: 10px;
        background-color: #fff;

        .row {
            display: flex;
            align-items: center;
            padding-top: 10px;
            background-color: #fff;

            .form_item {
                display: flex;
                align-items: center;
                margin-right: 10px;

                .label {
                    width: 80px;

                }
            }
        }
    }

    .main {
        height: calc(100% - 130px);
        overflow: hidden;
        position: relative;
        z-index: 2;
        background-color: #fff !important;

        .my_table {
            height: calc(100% - 60px);
            overflow: hidden;
            padding: 0 10px;
            background-color: #fff;
        }

        .bottom {
            height: 100px;

            .total {
                display: flex;
                align-items: center;
                height: 40px;
                line-height: 40px;
                text-indent: 10px;
                background-color: #fff;

                &>div {
                    margin-right: 20px;
                }
            }

            .btns {
                padding: 10px;
            }

        }
    }

}

//打印相关
.print_wrap {
    .title {
        text-align: center;
        line-height: 1.5;
        font-size: 38px;
    }

    background-color: #fff;
    color: #000;
    width: 800px; //这里一定设置为600px 经过测试后的合适距离
   
    box-sizing:border-box;
    // font-weight: bold;
    font-size:36px;
    position: absolute;
    top: 0;
    left:0;
    z-index: -10;

    .line {
        width: 100%;
        border-top: 1px dashed #000;
        height: 1px;
        margin: 15px 0;
    }

    .margin_bottom_placeholder {
        //这里使用空div 站位 下边距
        width: 100%;
        height: 300px;

    }

    .flex {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .discount {
        text-align: right;
    }
}
</style>